package com.xiaoyun.alllearning.filter;


import com.xiaoyun.alllearning.domain.constant.SysConstants;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.core.annotation.Order;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
import java.util.UUID;

@WebFilter(urlPatterns = "/*")
@Order(1)
@Slf4j
public class TraceIdFilter implements Filter {


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String traceId = servletRequest.getParameter(SysConstants.TRACE_ID);
        //为空设置默认值
        if (StringUtils.isEmpty(traceId)) {
            traceId = UUID.randomUUID().toString();
        }
        MDC.put(SysConstants.TRACE_ID, traceId);

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
